#coding: utf-8

from flask import current_app, render_template, request, redirect, url_for, abort
from flask_login import current_user, login_required
from app.web import web
from app.models.book import BookCatalog, Book
from app.models.site import SiteMeta


@web.route("/")
@login_required
def index():
    
    page = request.args.get("page", 1, type=int)
    per_page = current_app.config["PER_PAGE"]

    if current_user.access == 1:
        catalogs = BookCatalog.page_admin(page, per_page)
    else:
        catalogs = BookCatalog.page_user(page, per_page)

    metas = SiteMeta.all()
    site = dict([(meta.name, meta.value) for meta in metas])

    return render_template("web/index.html", catalogs=catalogs, site=site)


@web.route("/book/<int:id>")
@web.route("/book/<int:id>-<int:catalog_id>")
@login_required
def reader(id, catalog_id=None):
    book = Book.get(id)
    if not book:
        return abort(404)
    if book.access == 0 and current_user.access == 0 and current_user.id != book.user_id:
        return abort(404)
    if book.user_id == current_user.id or book.access == 2 or current_user.access == 1:
        can_edit = True
    else:
        can_edit = False
    if catalog_id:
        catalog = BookCatalog.reader(book.id, catalog_id)
        if not catalog:
            return redirect(url_for("web.reader", id=book.id, can_edit=can_edit))
    else:
        catalog = BookCatalog.reader(book.id)
    if not catalog:
        return render_template("web/reader.html", book=book, can_edit=can_edit)
    prev = BookCatalog.prev(catalog)
    next = BookCatalog.next(catalog)
    catalogs = book.tree_catalogs()

    return render_template("web/reader.html", book=book,
                           catalogs=catalogs, catalog=catalog, can_edit=can_edit)

